package io.zcoder.innoway.rest;

import android.content.Context;
import android.os.Build;

import com.squareup.okhttp.OkHttpClient;

import io.zcoder.innoway.BuildConfig;
import io.zcoder.innoway.commons.PrefUtils;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;

public final class RestClient {
    private static Context applicationContext;
    private static final String BASE_URL = "http://api-dev.innoway.zcoder.io:8989";

    private RestClient() {
    }

    public static void setApplicationContext(Context context) {
        if (applicationContext == null) {
            applicationContext = context;
        }
    }

    /**
     * Build API service
     *
     * @return API Service instance
     */
    public static ApiService build(final Context context, final boolean auth) {

        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestInterceptor.RequestFacade request) {
                request.addHeader("Accept", "application/json");
                if (auth) {
                    request.addHeader("X-AUTH-TOKEN", PrefUtils.getString(context, PrefUtils.PREF_AUTHEN_TOKEN));
                }
            }
        };

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(BASE_URL)
                .setClient(new OkClient(new OkHttpClient()))
                .setRequestInterceptor(requestInterceptor)
                .setLogLevel(getLogLevel())
                .build();

        return restAdapter.create(ApiService.class);
    }


    private static RestAdapter.LogLevel getLogLevel() {
        return BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE;
    }
}
